package com.feige.handler;

import cn.hutool.core.util.StrUtil;
import com.feige.constant.Constants;
import com.feige.result.AjaxResult;
import com.feige.utils.http.ResponseUtil;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出业务类
 * @author feige
 */
public class TokenLogoutHandler implements LogoutSuccessHandler {


    private final RedisUtils redisUtils;

    private final JwtUtils jwtUtils;


    public TokenLogoutHandler(RedisUtils redisUtils, JwtUtils jwtUtils) {
        this.redisUtils = redisUtils;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader(Constants.TOKEN_KEY);
        if (StrUtil.isNotBlank(token)) {
            String userId = jwtUtils.getUserIdByToken(token);
            if (StrUtil.isNotBlank(userId)){
                //清空当前用户缓存中的权限数据
                redisUtils.del(Constants.LOGIN_USER_KEY + userId);
                ResponseUtil.out(response, AjaxResult.success());
            }
        }
        ResponseUtil.out(response, AjaxResult.error());
    }
}
